const Service = require('egg').Service;
const { error, success } = require('../utils/response.js')
const fs = require('fs');
const path = require('path')

class PokemonService extends Service {
    // 获取宝可梦 分页加筛选
    async getPage(info, ctx) {
        const limit = info.limit || 8;
        const page = info.page || 1;
        let { area, attribute,name } = info;
        if(!area) area = null;
        if(attribute === '') attribute = null;
        if(name === '') name = null;
        // 获取分页数据
        const res = await this.app.mysql.query(`select * from pokemon where (area = ? or ? is null) and (attribute like concat('%',?,'%') or ? is null) and (name like concat('%',?,'%') or ? is null) limit ? offset ?`, [area, area, attribute, attribute,name,name, Number(limit), (page - 1) * limit]);
        // 获取总页数
        const resTotal = await this.app.mysql.query(`select count(id) from pokemon where (area = ? or ? is null) and (attribute like concat('%',?,'%') or ? is null) and (name like concat('%',?,'%') or ? is null)`, [area, area, attribute, attribute,name,name]);
        const totalPage = Math.ceil(resTotal[0]['count(id)'] / limit)
        success(ctx, '获取成功', { totalPage, currentPage: Number(page), total: resTotal[0]['count(id)'], data: res })
    }

    // 根据id数组获取宝可梦信息
    async getPokemon(info, ctx){
        const {ids} = info;
        const idStr = JSON.parse(ids).join(',')
        const res = await this.app.mysql.query(`select * from pokemon where id in (${idStr})`);
        success(ctx, '获取成功', res)
    }

    // 添加宝可梦功能  需要登录权限
    async add(info, file, ctx) {
        if (!file) return error(ctx, '请上传精灵图片')
        // 先检查图鉴编号是否占用
        const has = await this.app.mysql.get('pokemon', { id: info.id });
        if (has) return error(ctx, '已存在该编号的精灵')
        // 存储图片
        let filedata = fs.readFileSync(file.filepath);
        // 获取文件扩展名
        const fext = path.extname(file.filepath);
        const filePath = `/public/images/pokemon/${info.id}${fext}`
        fs.writeFileSync(path.join(__dirname, `..${filePath}`), filedata);
        info.image = filePath;
        const res = await this.app.mysql.insert('pokemon', { ...info });
        if (res.affectedRows !== 1) error(ctx, '添加宝可梦失败！请检查后台服务')
        success(ctx, '添加成功！')
    }
    // 更新宝可梦信息
    async update(info, file, ctx){
        if (!file) return error(ctx, '请上传精灵图片')
        // 先检查图鉴编号是否存在
        const has = await this.app.mysql.get('pokemon', { id: info.id });
        if (!has) return error(ctx, '不存在该编号精灵')
        // 存储图片
        let filedata = fs.readFileSync(file.filepath);
        // 获取文件扩展名
        const fext = path.extname(file.filepath);
        const filePath = `/public/images/pokemon/${info.id}${fext}`
        fs.writeFileSync(path.join(__dirname, `..${filePath}`), filedata);
        info.image = filePath;
        const res = await this.app.mysql.update('pokemon', { ...info });
        if (res.affectedRows !== 1) error(ctx, '更新宝可梦失败！请检查后台服务')
        success(ctx, '更新成功！')
    }
    // 根据id删除宝可梦
    async delete(info, ctx){
        const {id} = info;
        const res = await this.app.mysql.delete('pokemon',{id});
        if(res.affectedRows !== 1) error(ctx, '删除宝可梦失败！请检查后台服务')
        success(ctx, '删除成功')
    }
}
module.exports = PokemonService;